import matplotlib.pyplot as plt
import pandas as pd
from sklearn.linear_model import LinearRegression
from sklearn.model_selection import train_test_split
from sklearn.model_selection import cross_val_predict
plt.rcParams['font.sans-serif'] = ['SimHei']  # 用来正常显示中文标签
plt.rcParams['axes.unicode_minus'] = False  # 用来正常显示负号

plt.rcParams['figure.figsize'] = (8.0, 4.0)


class Regression:
    def __init__(self, dataset, args):
        self.dataset = dataset

    def run(self):
        data = pd.read_table(self.dataset, sep=',', header=None)
        X = data.iloc[:, :9]
        y = data.iloc[:, 9]

        X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=1)

        linreg = LinearRegression()
        linreg.fit(X_train, y_train)

        predicted = cross_val_predict(linreg, X_test, y_test, cv=10)
        predicted = predicted.tolist()
        y_new = y_test.values.tolist()
        y_show = [float(('%.3g' % (predicted[i]-y_new[i]))) for i in range(len(predicted))]
        loss = '%.3g' % (sum(y_show) / len(y_show))

        return {
            'Loss': float(loss),
            'PredictTruthLoss': y_show[:100],
            'Description': '本算法为食品预警回归预测算法，由于源数据分布相同，因此可认为数据均分布在一条回归曲线上。'
                           '通过训练集检测值及对应的预警值，来预测测试集的食品预警值，图中展示了测试集中100条数据的真实预警值和预测预警值的差。'
        }


if __name__ == '__main__':
    print(Regression('../../data/sterilizedmilk_for_regression.csv', {}).run())


